package org.teamh.connection.json.handler;

import org.teamh.connection.json.event.JsonEventObject;
import org.teamh.game.Start;
import org.teamh.logic.datamodel.*;

public class CellHandler extends JsonMasterHandler {

	public CellHandler(Start start, DatamodelManager manager) {
		super(start, manager);
	}
	
	public boolean handleMsg(JsonEventObject json) {
		
		if (json.getSource().startsWith("Cell")) {
			if (json.getProperty().equals("map")) {
				Map map = manager.getMap(json.getNewValue());
				if(map == null) {
					map = new Map(json.getNewValue());
				}
				manager.getCell(json.getSource()).setMap(map);
				return true;
			} else if (json.getProperty().equals("type")) {
				manager.getCell(json.getSource()).setType(json.getNewValue());
				return true;
			} else if (json.getProperty().equals("x")) {
				manager.getCell(json.getSource()).setX(Integer.parseInt(json.getNewValue()));
				return true;
			} else if (json.getProperty().equals("y")) {
				manager.getCell(json.getSource()).setY(Integer.parseInt(json.getNewValue()));	
				return true;
			} else if (json.getProperty().equals("elements")) {
				if (json.getNewValue() != null) {
					if (json.getNewValue().contains("Tower")) {
						manager.getCell(json.getSource()).setTower(manager.getTower(json.getNewValue()));
//						System.out.println("on this cell a tower is now standing: " + manager.getTower(json.getNewValue()).getID());
					} else if(json.getNewValue().contains("Creep")) {
						manager.getCell(json.getSource()).addCreep(manager.getCreep(json.getNewValue()));
					}
				} else if(json.getOldValue() != null) {
					if(json.getOldValue().contains("Tower")) {
						Cell cell = manager.getCell(json.getSource());
						if(cell != null) {
							cell.setTower(null);
						}
					} else if(json.getOldValue().contains("Creep")) {
						Cell cell = manager.getCell(json.getSource());
						Creep creep = manager.getCreep(json.getOldValue());
						if(cell != null && creep != null) {
							cell.removeCreep(creep);
						}
					}
				}
				
				return true;
			}
			return false;
		} else {
			return false;
		}	
	}
}